import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";

export const fetchSettimeout = createAsyncThunk(
  "counter/fetchSettimeout",
  (id: number) => {
    return new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(id);
      }, 3000);
    });
  }
);

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    isLogin: false,
    value: 0,
    featchVal: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchSettimeout.fulfilled, (state, action) => {
      console.log(state, action);
      state.featchVal = action.payload;
    });
  },
});

// reducers当中的方法会放在counterSlice的actions中, 用于派发action
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// 注意: 导出的是reducer, 用于在index.js中对reducer进行组合
export default counterSlice.reducer;
